﻿using FB.Membership;
using FB.Membership.Principal;
using FB.Providers;
using System;
using System.Linq;
using System.Web.Security;
using FB.Extensions;
using FB.Data.Models;

namespace FB.Services
{
    public class AccountServiceBase : IAccountService
    {
        LoggingService _LOGSVR;
        public AccountServiceBase()
        {
            _LOGSVR = new FB.Services.LoggingService();
        }

        public void SetAuthenCookie(string userName, bool createPersistentCookie = false)
        {
            var membershipWrapper = new AspNetMembershipProviderWrapper();
            userName = userName.ToLower();
            var membership = membershipWrapper.Get(userName);
            var userKey = (Guid)membership.ProviderUserKey;
            
            var cookieModel = new FBIdentityCookieModel
            {
                Name = membership.UserName,
                UserId = userKey,
            };

            cookieModel.Services = membershipWrapper.GetService(userName);
            cookieModel.UserType = membershipWrapper.GetUserType(userKey);

            // set permission
            PermissionManager.PermissionSession = PermissionManager.GetUserPermissions(membership);

            // set role
            AspNetRoleProviderWrapper.RoleSession = System.Web.Security.Roles.GetRolesForUser(userName);

            // set cookie
            FormsAuthenticationWrapper.SetAuthCookie(userName, createPersistentCookie, cookieModel);

            #region Logging
            _LOGSVR.LogAccess( membership.UserName, FB.Enums.AccessStatus.Sign_In);
            #endregion
        }



        //public void SignOutAndCleanSession(string username)
        public void SignOutAndCleanSession(FBIdentity identity)
        {
            FormsAuthentication.SignOut();
            System.Web.HttpContext.Current.Session.Abandon();

			
            if (null != identity)
            {
                #region Logging
                _LOGSVR.LogAccess(identity.Name, FB.Enums.AccessStatus.Sign_Out);
                #endregion
            }
        }

        #region Static Method


        public static void UpdatePermissionAndRole()
        {
            var user = System.Web.HttpContext.Current.User;
            if (user.Identity.IsAuthenticated)
            {
                var membership = System.Web.Security.Membership.GetUser(user.Identity.Name);
                PermissionManager.PermissionSession = PermissionManager.GetUserPermissions(membership);
                AspNetRoleProviderWrapper.RoleSession = System.Web.Security.Roles.GetRolesForUser(user.Identity.Name);
            }
        }

        #endregion


    }
}
